package com.tensquare.base.service;


import com.tensquare.base.dao.LabelDao;
import com.tensquare.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.LinkedList;
import java.util.List;

@Service
public class LabelService {
  @Autowired
  private LabelDao labelDao;
  @Autowired
  private IdWorker idWorker;
  /*
    查询全部标签
    @return
   */
  public List<Label> findAll(){
    return labelDao.findAll();
  }
  /*
    根据ID查询标签
   */
  public Label findById(String id){
    return labelDao.findById(id).get();
  }
  /*
    增加标签
   */
  public void add(Label label){
    label.setId(idWorker.nextId()+"");//设置ID
    labelDao.save(label);
  }
  /*
    修改标签
   */
  public void update(Label label){
    labelDao.save(label);
  }
  /*
    根据id删除标签
   */
  public void deleteById(String id){
    labelDao.deleteById(id);
  }

  public List<Label> findSearch(Label label) {

    return labelDao.findAll(getLabelSpecification(label));

  }
  //label的条件查询
  private Specification<Label> getLabelSpecification(Label label){
    return new Specification<Label>() {
      /**
       *
       * @param root 根对象,也就是吧条件封装到哪个对象中 where 类名 = label.getid
       * @param query 封装的都是查询关键字,比如group by ,order by等
       * @param cb 用来封装条件对象的
       * @return
       */
      @Override
      public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        String labelName = label.getLabelname();
        String labelState = label.getState();

        //需要使用一个predicate数组来存放所有条件
        List<Predicate> predicates = new LinkedList<>();

        if( !StringUtils.isEmpty(labelName) ){
          //where labelname like %xiaoming%
          Predicate predicate = cb.like(root.get("labelname").as(String.class),"%"+labelName+"%");
          predicates.add(predicate);
        }
        if( !StringUtils.isEmpty(labelState) ){
          //where state = '1'
          Predicate predicate = cb.equal(root.get("state").as(String.class),labelState);
          predicates.add(predicate);
        }
        //new 一个数组作为最终返回值的条件
        Predicate [] parr = new Predicate[predicates.size()];
        //把list转成数组
        predicates.toArray(parr);//parr中已经赋值了
        return cb.and(parr);//相当于用and把各个条件连接起来

      }
    };
  }

  public Page<Label> pageQuery(Label label, int page, int size) {
    //封装分页对象
    Pageable pageable = PageRequest.of(page-1, size);//-1变成了从第一页开始
    return labelDao.findAll(getLabelSpecification(label), pageable);

  }
}
